package com.hanZhe.shiro.controller;


import com.hanZhe.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.omg.CORBA.PUBLIC_MEMBER;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;


/**
 * Created by shw on 2018-02-27.
 */

@Controller
@RequestMapping("/shiro")
public class ShiroController {

    //输出日志
    private Logger log = LoggerFactory.getLogger(ShiroController.class);

    @Autowired
    private UserService userService;


    @RequestMapping("/test")

    public ModelAndView test(){
        ModelAndView modelAndView=new ModelAndView("list");
        try {
            userService.textMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return modelAndView;
    }



    /**
     * 执行登陆的方法
     * @param
     * @return
     * @author 尚和稳
     * @date 2018-02-27 9:26
     */
    @RequestMapping("/login")
    public String login(String username, String password, HttpServletRequest request){

        //获取remberMe
        String remberme = request.getParameter("remberme");
        log.info("----------remberMe"+remberme);

        //调用Securityutils的getSubject方法获取到当前的subject
        Subject currentUser = SecurityUtils.getSubject();
        //验证是否登陆
        if(!currentUser.isAuthenticated()){
            //如果没有登陆,将用户名和密码封装成user那么passwordtoken对象
            UsernamePasswordToken token=new UsernamePasswordToken(username,password);
            //获取前端的记住我选项
            if(remberme!=null){
                //rememberme,记住我
                token.setRememberMe(true);
            }else {
                token.setRememberMe(false);
            }



            try {
                //调用subject的login方法执行登陆
                currentUser.login(token);
            } catch (AuthenticationException e) {
                log.info("------------------->登陆失败"+e.getMessage());
            }

        }
        return "redirect:/list.jsp";
    }

}
